# -*- coding: utf-8 -*-
import random
import string
from wtforms import Form, StringField, validators
import pprint
#import urllib.parse
#import urllib.request
import base64
import json
#	import pycurl
import requests
import json
from datetime import datetime
from json import dumps
import base64

class PayGIntegration():
    #@var string This Request URL 
    paymentURL = 'https://uatapiv2.payg.in/payment/api/order' # UAT Base API
    # paymentURL = 'https://apiv2.payg.in/payment/api/order' #Production Base API

    #@var string AuthenticationKey For Payment Provided By PayG Gateway
    AuthenticationKey = '' #Take from PayG Team
    #@var string AuthenticationToken For Payment Provided By PayG Gateway
    AuthenticationToken  ='' #Take from PayG Team
    #@var  string SecureHashKey For Payment Provided By PayG Gateway 
    SecureHashKey  = '' #Optional
    #@var  string MID For Payment Provided By PayG Gateway.
    MID = '' #Take from PayG Team
    #@var  string RedirectUrl For Redirection Url which being redirected after payment checkout page. 
    RedirectUrl = 'https://payg.in'

    def __init__(self): 
        self.StringLength =10
    
    def get_random_string(StringLength):
        letters = string.ascii_lowercase
        result_str = ''.join(random.choice(letters) for i in range(StringLength))
        #print("Random string of length", StringLength, "is:", result_str)
        return result_str
    
    
        
    def orderCreate(self,post_data):
        #now = datetime.datetime.now()
        
        myfamily = {
            'MID':self.MID,
            'UniqueRequestId':PayGIntegration.get_random_string(15),
            'OrderAmount':post_data.get('OrderAmount'),
            'OrderType':post_data.get('OrderType'),
            "UserDefinedData" : {
                "UserDefined1" : ""		
            },
            "RequestDateTime":"",
            "RedirectUrl": self.RedirectUrl,
            "TransactionData" : {
                "AcceptedPaymentTypes" : "",
                "PaymentType" : "",
                "SurchargeType":"",
                "SurchargeValue":"",
                "RefTransactionId":"",
                "IndustrySpecificationCode":"",
                "PartialPaymentOption":""
            },
            'OrderAmountData':{
                "AmountTypeDesc":post_data.get('AmountTypeDesc'),
                "Amount":post_data.get('Amount')
            },
            "CustomerData":{
                "CustomerId":post_data.get('CustomerId'),
                "CustomerNotes":post_data.get('CustomerNotes'),
                "FirstName":post_data.get('FirstName'),
                "LastName":post_data.get('LastName'),
                "MobileNo":post_data.get('MobileNo'),
                "Email":post_data.get('Email'),
                "EmailReceipt":post_data.get('EmailReceipt'),
                "BillingAddress":post_data.get('BillingAddress'),
                "BillingCity":post_data.get('BillingCity'),
                "BillingState":post_data.get('BillingState'),
                "BillingCountry":post_data.get('BillingCountry'),
                "BillingZipCode":post_data.get('BillingZipCode'),
                "ShippingFirstName":post_data.get('ShippingFirstName'),
                "ShippingLastName":post_data.get('ShippingLastName'),
                "ShippingAddress":post_data.get('ShippingAddress'),
                "ShippingCity":post_data.get('ShippingCity'),
                "ShippingState":post_data.get('ShippingState'),
                "ShippingCountry":post_data.get('ShippingCountry'),
                "ShippingZipCode":post_data.get('ShippingZipCode'),
                "ShippingMobileNo":post_data.get('ShippingMobileNo'),
            },
            "IntegrationData":{
                "UserName":post_data.get("UserName"),
                "Source":post_data.get("Source"),
                "IntegrationType":post_data.get("IntegrationType"),
                "HashData":post_data.get("HashData"),
                "PlatformId":post_data.get("PlatformId"),
            }
        }

        message = self.AuthenticationKey+":"+self.AuthenticationToken+":M:"+self.MID
        message_bytes = message.encode('ascii')
        base64_bytes = base64.b64encode(message_bytes)
        base64_message = base64_bytes.decode('ascii')
        
        url = self.paymentURL+"/create"		
        payload = json.JSONEncoder().encode(myfamily);
        headers = {
        'content-type': "application/json",
        'authorization': "Basic "+base64_message
        }

        response = requests.request("POST", url, data=payload, headers=headers)
        response_json = response.json()
        print('**** Create API Response *******************')
        print('HTTP STATUS CODE: ',response)
        print('RESPONSE: ',response.text)
        PaymentProcessUrl = response_json.get("PaymentProcessUrl")
        # return json.loads(response.text)
        return {
            "responseData": json.loads(response.text),
            "requestBody": payload
        }
        
    def orderDetail(self,post_data):
        url = self.paymentURL+"/Detail"		
        message = self.AuthenticationKey+":"+self.AuthenticationToken+":M:"+self.MID
        message_bytes = message.encode('ascii')
        base64_bytes = base64.b64encode(message_bytes)
        base64_message = base64_bytes.decode('ascii')
        
        myfamily = {
            "OrderKeyId":post_data.get('OrderKeyId'),
            "MID":self.MID,
        }
        
        payload = json.JSONEncoder().encode(myfamily);
        headers = {
        'content-type': "application/json",
        'authorization': "Basic "+base64_message
        }

        response = requests.request("POST", url, data=payload, headers=headers)
        # pprint.pprint(payload)
        print('**** Detail API Response *******************')
        print('HTTP STATUS CODE: ',response)
        print('RESPONSE: ',response.text)
        
        # return json.loads(response.text)
        return {
            "responseData": json.loads(response.text),
            "requestBody": payload
        }
    

    